<?php
namespace Zxf5115\Laravel\Dictionary\Services;

use Illuminate\Support\Facades\Redis;
use Zxf5115\Laravel\Dictionary\Models\Platform\Dictionary;

/**
 * @author zhangxiaofei [<1326336909@qq.com>]
 * @dateTime 2025-09-23
 *
 * 系统字典服务类
 */
class DictionaryService
{
  /**
   * Redis缓存键名
   */
  protected string $redisKey;


  /**
   * 构造函数
   */
  public function __construct()
  {
    // 提前初始化Redis键，避免重复调用config()
    $this->redisKey = config('key.redis.dictionary');
  }


  /**
   * 根据字典标题获取字典缓存数据
   *
   * @param string $title 字典标题
   * @return array 字典数据
   */
  public function getCacheDataByTitle(string $title) : array
  {
    $response = [];

    if(Redis::connection('cache')->hexists($this->redisKey, $title))
    {
      $result = Redis::connection('cache')->hget($this->redisKey, $title);

      $response = json_decode($result, true);

      // 验证JSON解析结果
      if(json_last_error() !== JSON_ERROR_NONE)
      {
        // 删除无效缓存
        Redis::connection('cache')->hdel($this->redisKey, $title);
      }
    }
    else
    {
      // 缓存未命中，从数据库获取
      $model = Dictionary::whereTitle($title)->with('parameter')->first();

      if($model && !empty($model->parameter))
      {
        foreach($model->parameter as $item)
        {
          $response[$item->value]['text'] = $item->title;
          $response[$item->value]['value'] = $item->value;
        }

        $response = collect($model->parameter)->mapWithKeys(function ($item) {
          return [
            $item->value => ['text' => $item->title, 'value' => $item->value]
          ];
        })->all();

        Redis::connection('cache')->hset($this->redisKey, $title, json_encode($response));
        Redis::connection('cache')->expire($this->redisKey, 1296000); // 15天过期
      }
    }

    return $response;
  }


  /**
   * 根据字典标题删除字典缓存数据
   *
   * @param string $title 字典标题
   * @return void
   */
  public function deleteCacheDataByTitle(string $title) : void
  {
    Redis::connection('cache')->hdel($this->redisKey, $title);
  }
}
